package com.george.controller;

import com.george.entity.User;
import com.george.service.UserService;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import io.searchbox.core.Bulk;
import io.searchbox.core.BulkResult;
import io.searchbox.core.Index;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * <p>
 *
 * </p>
 *
 * @author GeorgeChan 2019/6/12 8:36
 * @version 1.0
 * @since jdk1.8
 */
@RestController
@RequestMapping("/es")
public class UserController {
    private static JestClient jestClient;
    private static String indexName = "userindex";
    private static String typeName = "user";
    private static String elasticIps="http://192.169.116.132:9200";
    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    private static  JestClient getJestClient() {
        JestClientFactory factory = new JestClientFactory();
        factory.setHttpClientConfig(new HttpClientConfig.Builder(elasticIps).connTimeout(60000).readTimeout(60000).multiThreaded(true).build());
        return factory.getObject();
    }

    @PostMapping("/insert")
    public boolean insert() throws IOException {
        jestClient = getJestClient();
        Bulk.Builder bulk = new Bulk.Builder().defaultIndex(indexName).defaultType(typeName);
        User user = new User(1L, "张三", 20, "张三是个Java开发工程师","2018-4-25 11:07:42");
        Index index = new Index.Builder(user).build();
        bulk.addAction(index);
        BulkResult br = jestClient.execute(bulk.build());
        jestClient.close();
        return br.isSucceeded();
    }

    public void insertBatch() {

    }
}
